# 菜 鸟 上 线 ： 目标实习一个W
# 菜      鸟：  陈 思 危
# 上 线 时 间：  2024/6/14 16:16
import pymysql
from pyecharts.charts import Pie
from pyecharts import options

# 建立数据库连接
db = pymysql.connect(
    host="localhost",
    user="root",
    password="csw.427.",
    database="crawlerdemo",
    charset="utf8"
)

# 创建游标对象
cursor = db.cursor()

# SQL查询，用来查找岗位数量最多的五个城市
sql = "select job_place, count(job_id) from job group by job_place order by count(job_id) desc limit 5"

try:
    cursor.execute(sql)
    res = cursor.fetchall()

    # 计算总岗位数量
    total_jobs = sum([row[1] for row in res])

    # 计算每个城市的岗位占比
    data = [(row[0], round((row[1] / total_jobs) * 100, 2)) for row in res]

    pie = Pie()

    # 添加数据到饼图，并设置数据标签显示百分比
    pie.add("岗位占比", data)

    pie.set_global_opts(
        title_opts=options.TitleOpts(title="岗位数量最多的五个城市的占比"),
        legend_opts=options.LegendOpts(is_show=False)
    )

    pie.set_series_opts(
        label_opts=options.LabelOpts(formatter="{b}: {d}%")
    )

    # 渲染图表到HTML文件
    pie.render("piera.html")
except:
    print("查询出错啦")
finally:
    cursor.close()
    db.close()